package mvc.core.log;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义日志工具
 * 
 * @author liuzy
 * @version 2015年5月16日
 */
public class Logger {

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private String clazzName;

	public static String level = "INFO";

	private Logger(String clazzName) {
		this.clazzName = clazzName;
	}

	public static Logger getLogger(Class<?> clazz) {
		return new Logger(clazz.getName());
	}

	public void debug(String message) {
		if ("DEBUG".contains(level))
			this.log("[DEBUG]", message);
	}

	public void debug(String message, Throwable t) {
		if ("DEBUG".contains(level))
			this.log("[DEBUG]", message, t);
	}

	public void info(String message) {
		if ("DEBUG INFO".contains(level))
			this.log("[INFO ]", message);
	}

	public void info(String message, Throwable t) {
		if ("DEBUG INFO".contains(level))
			this.log("[INFO ]", message, t);
	}

	public void warn(String message) {
		if ("DEBUG INFO WARN".contains(level))
			this.log("[WARN ]", message);
	}

	public void warn(String message, Throwable t) {
		if ("DEBUG INFO WARN".contains(level))
			this.log("[WARN ]", message, t);
	}

	public void error(String message) {
		this.log("[ERROR]", message);
	}

	public void error(String message, Throwable t) {
		this.log("[ERROR]", message, t);
	}

	private void log(String level, String message) {
		StackTraceElement ste = Thread.currentThread().getStackTrace()[3];
		StringBuilder sb = new StringBuilder();
		sb.append(level).append(" ").append(sdf.format(new Date()));
		sb.append(" ").append(clazzName).append(".").append(ste.getMethodName());
		sb.append("(").append(ste.getFileName()).append(":");
		sb.append(ste.getLineNumber()).append(") ").append(message);
		System.out.println(sb.toString());
	}

	private void log(String level, String message, Throwable t) {
		StackTraceElement ste = Thread.currentThread().getStackTrace()[3];
		StringBuilder sb = new StringBuilder();
		sb.append(level).append(" ").append(sdf.format(new Date()));
		sb.append(" ").append(clazzName).append(".").append(ste.getMethodName());
		sb.append("(").append(ste.getFileName()).append(":");
		sb.append(ste.getLineNumber()).append(") ").append(message);
		System.out.println(sb.toString());
		t.printStackTrace(System.out);
	}

}
